package com.hq.web.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class DateTimeUtil {

	public static final String YYYY_MM_DD = "yyyy-MM-dd";
	public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd hh:mm:ss";

	public String prevMonthFormater = "yyyy-M";

	// 提供给 Spring 注入
	public void setPrevMonthFormater(String prevMonthFormater) {
		this.prevMonthFormater = prevMonthFormater;
	}

	// 锁对象 用于多线程同步
	private static final Object lockObj = new Object();

	// 存放不同的日期格式的sdf
	private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>();

	/**
	 * 返回一个ThreadLocal的sdf, 每个线程只会new一次sdf
	 * 
	 * @param pattern
	 * @return
	 */
	private static SimpleDateFormat getSdf(final String pattern) {
		ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
		// 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf
		if (tl == null) {
			synchronized (lockObj) {
				tl = sdfMap.get(pattern);
				if (tl == null) {
					// 这里是关键,使用ThreadLocal<SimpleDateFormat>替代原来直接new
					// SimpleDateFormat
					tl = new ThreadLocal<SimpleDateFormat>() {

						@Override
						protected SimpleDateFormat initialValue() {
							return new SimpleDateFormat(pattern);
						}
					};
					sdfMap.put(pattern, tl);
				}
			}
		}
		return tl.get();
	}

	public String getPrevMonth() {
		Calendar nowCal = Calendar.getInstance();
		nowCal.add(Calendar.MONTH, -1); // -1 标识当前月向前倒1个月
		SimpleDateFormat prevMonthFormat = new SimpleDateFormat(prevMonthFormater, Locale.CHINA);
		String prevDatetimeStr = prevMonthFormat.format(nowCal.getTime());
		return prevDatetimeStr;
	}

	public static String getDateStr(Date jobDate, String datePatternStr) {
		// 处理
		jobDate = null == jobDate ? new Date() : jobDate;
		datePatternStr = (null == datePatternStr || "".equals(datePatternStr)) ? DateTimeUtil.YYYY_MM_DD
				: datePatternStr;
		return getSdf(datePatternStr).format(jobDate);
	}

	/**
	 * 获取两个日期时间之间的秒数
	 * 
	 * @param smdate
	 * @param bgdate
	 * @return
	 * @throws ParseException
	 */
	public static int getSecsBetween(Date smdate, Date bgdate) throws ParseException {
		smdate = null == smdate ? new Date() : smdate;
		bgdate = null == bgdate ? new Date() : bgdate;
		return (int) ((bgdate.getTime() - smdate.getTime()) / 1000);
	}

}
